/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bda.mediatheque.service;

import com.bda.mediatheque.entities.Utilisateur;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

/**
 *
 * @author samsung
 */
public abstract class ImplJpaDao<K, E> implements IDao<K, E> {

    protected Class<E> entityClass;
    EntityManagerFactory emf = javax.persistence.Persistence.createEntityManagerFactory("MediaPU");
    EntityManager entityManager = emf.createEntityManager();

    public ImplJpaDao() 
    {
        ParameterizedType genericSuperclass =
                (ParameterizedType) getClass().getGenericSuperclass();
        this.entityClass = (Class<E>) genericSuperclass.getActualTypeArguments()[1];
    }

    @Override
    public void persist(E entity) 
    {
        entityManager.getTransaction().begin();
        try {
            entityManager.persist(entity);
            entityManager.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
            entityManager.getTransaction().rollback();
        } finally {
            entityManager.close();
        }
    }

    public void remove(E entity) 
    {
        entityManager.getTransaction().begin();
        try {
            entityManager.remove(entity);
            entityManager.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
            entityManager.getTransaction().rollback();
        } finally {
            entityManager.close();
        }
    }
    
    @Override
    public void merge(E entity) 
    {
        entityManager.getTransaction().begin();
        try {
            entityManager.merge(entity);
            entityManager.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
            entityManager.getTransaction().rollback();
            entityManager.close();
        } finally {
            
        }
    }
        
	public void update(E entity) 
	{
        entityManager.getTransaction().begin();
        try {
            entityManager.merge(entity);
            entityManager.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
            entityManager.getTransaction().rollback();
        } finally {
            entityManager.close();
        }
    }
	
    public E findById(K id)
    {
        return entityManager.find(entityClass, id);
    }
    
    public List<E> findAll() 
    {
        return  entityManager.createQuery("select e from "+ entityClass.getSimpleName()+" e").getResultList();
    }
}
